package com.sendpo.zjx.sendpo.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.BuildConfig;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.PrivateGenicInfoDomain;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.table.UserAddress;
import com.sendpo.zjx.sendpo.utils.MD5Util;
import com.sendpo.zjx.sendpo.utils.PayDomain;
import com.sendpo.zjx.sendpo.utils.PayResult;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BottomDialog;

/**
 * Created by 朱俊鑫 on 2018
 */

public class PrivateGenicInfoActivity extends AppCompatActivity {

    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.backbt)
    RelativeLayout backbt;
    public int id = 0;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.createbuy_bt)
    Button createbuyBt;

    @BindView(R.id.select_img)
    ImageView selectImg;
    PrivateGenicInfoDomain domain;
    public UserAddress userAddress = null;
    public static final int SELECTED_ADDRESS = 1001;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.shengao_edit)
    EditText shengaoEdit;
    @BindView(R.id.weight_edit)
    EditText weightEdit;
    @BindView(R.id.ac_level)
    TextView acLevel;
    @BindView(R.id.color_tv)
    TextView colorTv;
    @BindView(R.id.color_bt)
    RelativeLayout colorBt;
    @BindView(R.id.storeaddress_tv)
    TextView storeaddressTv;
    @BindView(R.id.address_right)
    ImageView addressRight;
    @BindView(R.id.storeaddress_bt)
    RelativeLayout storeaddressBt;
    @BindView(R.id.edit_active)
    EditText editActive;
    private BottomDialog bottomDialog;
    LinearLayout  imgs_selected;

    public int select_img=0;
    private String orderId="";
    private Dialog paydialog;
    private Dialog confirm_dialog;
    private RadioGroup radioGroup;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HttpUrl.SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Gson gson=new Gson();
                        PayDomain pay=gson.fromJson(payResult.getResult(),PayDomain.class);
//                          paysuccess(orderId);
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        System.out.println("***************"+payResult.getResult());
                        Toast.makeText(getApplicationContext(), "支付成功", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(getApplicationContext(), "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        };
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Tools.initStatus(this, R.color.black);
        setContentView(R.layout.activity_privategenicinfo);
        ButterKnife.bind(this);
        initComponent();
        initPayDialog();
    }
    public void  initPayDialog(){
        confirm_dialog=new Dialog(this);
        confirm_dialog.setContentView(R.layout.dialog_paymoney);
        confirm_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        final EditText confirm_edit_tv=confirm_dialog.findViewById(R.id.edit_tv);
        TextView exitbt=confirm_dialog.findViewById(R.id.exitbt);
        exitbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                confirm_dialog.dismiss();
            }
        });
        TextView readby=confirm_dialog.findViewById(R.id.readby);
        readby.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println("***********************readby");
                if(TextUtils.isEmpty(confirm_edit_tv.getText().toString().trim())){
                    Toast.makeText(getApplicationContext(),"支付密码不能为空",Toast.LENGTH_LONG).show();
                    return;
                }
                List<User> userList= Xutils.queryAll(getApplication(),User.class);
                if(userList==null){
                    return;
                }
                User user=userList.get(0);
                if(TextUtils.equals(MD5Util.getMD5(confirm_edit_tv.getText().toString().trim()), user.getUserPaypassword())){
                    Toast.makeText(getApplicationContext(),"输入密码正确",Toast.LENGTH_LONG).show();
                  yuyue(orderId,user.getUserId()+"");
                }else{
                    Toast.makeText(getApplicationContext(),"输入支付密码不正确",Toast.LENGTH_LONG).show();
                }

            }
        });

        paydialog=new Dialog(this);
        paydialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        paydialog.setContentView(R.layout.dialog_rechargemoney);
        radioGroup=paydialog.findViewById(R.id.rg_pay);
        TextView recharage_title=paydialog.findViewById(R.id.recharage_title);
        recharage_title.setText("结算支付");
        EditText recharge_edit= paydialog.findViewById(R.id.recharge_edit);
        recharge_edit.setVisibility(View.GONE);
        View yuyue_left=paydialog.findViewById(R.id.yuyue_left);
        yuyue_left.setVisibility(View.VISIBLE);
        final RadioButton pay_moneypackage=paydialog.findViewById(R.id.pay_moneypackage);
        pay_moneypackage.setVisibility(View.VISIBLE);
        pay_moneypackage.setChecked(true);
        final RadioButton pay_wexin=paydialog.findViewById(R.id.pay_wexin);
        pay_wexin.setChecked(false);
        paydialog.findViewById(R.id.moneycount_rl);

        Button paybt=paydialog.findViewById(R.id.paybt);

        paybt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<User> userList= Xutils.queryAll(getApplication(),User.class);
                if(userList==null){
                    return;
                }
                User user=userList.get(0);
                switch (radioGroup.getCheckedRadioButtonId()){
                    case R.id.pay_moneypackage:
                        if(TextUtils.isEmpty(user.getUserPaypassword())){
                            Intent paypass=new Intent(PrivateGenicInfoActivity.this,ModifyPayPassActivity.class);
                            startActivity(paypass);
                            return;
                        }
                        paydialog.dismiss();
                        confirm_edit_tv.getText().clear();
                        confirm_dialog.show();
                        break;
                    case R.id.pay_wexin:
                        Toast.makeText(getApplicationContext(),"微信支付"
                                ,Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.pay_paypackage:
                        Toast.makeText(getApplicationContext(),"支付宝支付"
                                ,Toast.LENGTH_SHORT).show();
                      zhifubao(orderId,user.getUserId()+"");
                        //paymoney
//                        if(jifentype==1){
//                            int number=Integer.parseInt(dataBean.getMerchandiseKouchujifen())*num;
//                            if(Integer.parseInt(user.getUserJifen())-number<0){
//                                Toast.makeText(getApplicationContext(),"积分不足！无法购买",Toast.LENGTH_SHORT).show();
//                                return;
//                            }
//                        }

                        break;
                }
            }
        });
        yuyue_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_moneypackage.setChecked(true);
            }
        });
        RelativeLayout wx_rl=paydialog.findViewById(R.id.wx_rl);
        wx_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_wexin.setChecked(true);
            }
        });
        final RadioButton pay_paypackage=paydialog.findViewById(R.id.pay_paypackage);
        RelativeLayout pay_rl=paydialog.findViewById(R.id.pay_rl);
        pay_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_paypackage.setChecked(true);
            }
        });


    }

    public void initComponent() {
        id = getIntent().getIntExtra("id", 0);
        getInfo(id);

    }

    @OnClick(value = {R.id.backbt, R.id.storeaddress_bt, R.id.createbuy_bt,R.id.color_bt})
    public void onMyClick(View view) {
        List<User> userList=Xutils.queryAll(getApplication(),User.class);
        if(userList==null||userList.size()==0){
            Tools.redirectActivity(this,LoginActivity.class);
            return;
        }
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case R.id.storeaddress_bt:


                Intent selectaddress = new Intent(this, AddressListActivity.class);
                startActivityForResult(selectaddress, SELECTED_ADDRESS);
                break;
            case R.id.createbuy_bt:

                if(!TextUtils.isEmpty(orderId)){
                    Toast.makeText(getApplicationContext(),"已经生成订单，请支付",Toast.LENGTH_SHORT).show();
                    paydialog.show();
                    return;
                }
                if (TextUtils.isEmpty(shengaoEdit.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), "请填写身高", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(weightEdit.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), "请填写体重", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(colorTv.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), "请选择款式", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (userAddress == null) {
                    Toast.makeText(getApplicationContext(), "请选择地址信息", Toast.LENGTH_SHORT).show();
                    Intent address = new Intent(this, AddressListActivity.class);
                    startActivityForResult(address, SELECTED_ADDRESS);
                    return;
                }

                  JSONObject jsonObject=new JSONObject();
                try {
                    jsonObject.put("userId",userList.get(0).getUserId());
                    jsonObject.put("userAddressId",userAddress.getAddressId());
                    jsonObject.put("designId",id);
                    jsonObject.put("count",1);
                    jsonObject.put("remarks",editActive.getText().toString().trim()+"");
                    jsonObject.put("deliveryType",0);
                  JSONArray relations=new JSONArray();

                    JSONObject da1=new JSONObject();
                    da1.put("componentType","身高");
                    da1.put("componentValue",""+shengaoEdit.getText().toString().trim());
                    JSONObject da2=new JSONObject();
                    da1.put("componentType","体重");
                    da1.put("componentValue",""+weightEdit.getText().toString().trim());
                    relations.put(da1);
                    relations.put(da2);
                    jsonObject.put("relations",relations.toString());
                    JSONArray formats=new JSONArray();
                    JSONObject formats1=new JSONObject();
                    formats1.put("formatId",domain.getData().getDetails().get(0).getTitle().getId());
                    formats1.put("imgId",select_img);
                    formats.put(formats1);
                    jsonObject.put("formats",formats.toString());
                    submitOrder(jsonObject);
                } catch (JSONException e) {
                    e.printStackTrace();
                }


                break;
            case R.id.color_bt:
            if(bottomDialog!=null){
                bottomDialog.show();
            }

                break;
        }
    }

    public void getInfo(int id) {
        Map<String, String> map = new HashMap<>();
        map.put("id", id + "");
        Xutils.GET(HttpUrl.customizegetById, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                domain = gson.fromJson(result, PrivateGenicInfoDomain.class);
                if (domain.isFlag()) {
                    Glide.with(PrivateGenicInfoActivity.this)
                            .load(domain.getData().getImg())
                            .asBitmap()
                            .centerCrop()
                            .animate(R.anim.fade_in)
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                    selectImg.setImageBitmap(resource);
                                }
                            });
                    bottomDialog = BottomDialog.create(getSupportFragmentManager());
                    bottomDialog.setViewListener(new BottomDialog.ViewListener() {
                        @Override
                        public void bindView(View v) {
                            v.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    bottomDialog.dismiss();
                                }
                            });
                            v.findViewById(R.id.closebt).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    bottomDialog.dismiss();
                                }
                            });
                            imgs_selected =v.findViewById(R.id.imgs_selected);
                            if(domain!=null&&domain.getData()!=null&&domain.getData().getDetails().get(0).getValue()!=null&&
                                    domain.getData().getDetails().get(0).getValue().size()!=0){
                                    select_img=domain.getData().getDetails().get(0).getValue().get(0).getId();
                                for(int i=0;i<domain.getData().getDetails().get(0).getValue().size();i++){
                                    final PrivateGenicInfoDomain.DataBean.DetailsBean.ValueBean valueBean=domain.getData().getDetails().get(0).getValue().get(i);
                                    View view=View.inflate(PrivateGenicInfoActivity.this,R.layout.layout_dingzi_styleitem,null);
                                    TextView     uname=view.findViewById(R.id.name);
                                    uname.setText(""+valueBean.getTitle());
                                    ImageView iv=view.findViewById(R.id.img);
                                    Glide.with(PrivateGenicInfoActivity.this)
                                            .load(""+valueBean.getImg())
                                            .asBitmap()
                                            .animate(R.anim.fade_in)
                                            .into(iv);
                                    view.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            select_img=valueBean.getId();
                                            colorTv.setText(valueBean.getTitle());
                                            Glide.with(PrivateGenicInfoActivity.this)
                                                    .load(valueBean.getImg()+"")
                                                    .asBitmap()
                                                    .centerCrop()
                                                    .animate(R.anim.fade_in)
                                                    .into(new SimpleTarget<Bitmap>() {
                                                        @Override
                                                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                                            selectImg.setImageBitmap(resource);
                                                        }
                                                    });
                                            bottomDialog.dismiss();
                                        }
                                    });
                                    imgs_selected.addView(view);
                                }

                            }

                        }
                    });
                    bottomDialog.setLayoutRes(R.layout.dialog_dingzi_rl);
                    bottomDialog.setDimAmount(0.5f);
                    bottomDialog.setCancelOutside(true);
                    bottomDialog.setTag("BottomDialog");
                } else {
                    Toast.makeText(getApplicationContext(), "定制方案，是否存在", Toast.LENGTH_SHORT).show();
                }

                name.setText(domain.getData().getTitle());
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case SELECTED_ADDRESS:
                if (data != null) {
                    userAddress = (UserAddress) data.getSerializableExtra("address_data");
                    address.setText("" + userAddress.getUserCity() + userAddress.getUserDetailedAddress());
                   }
                break;
        }

    }


    public void submitOrder(JSONObject jsonObject){
        RequestParams requestParams=new RequestParams(HttpUrl.customizegenerateOrder);
          requestParams.setMultipart(true);
          requestParams.setAsJsonContent(true);
          System.out.println("*********************************"+jsonObject.toString());
          requestParams.setBodyContent(jsonObject.toString());
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject1=new JSONObject(result);
                    if(jsonObject1.getBoolean("flag")){
                        orderId= jsonObject1.getInt("data")+"";
                        paydialog.show();
                        Toast.makeText(getApplicationContext(),"定制生成订单成功",Toast.LENGTH_SHORT).show();
                        System.out.println("*************************jsonObject1*toString****"+jsonObject1.toString());
                    }else{
                        Toast.makeText(getApplicationContext(),"定制生成订单失败",Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getApplicationContext(),"请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }



    //余额支付
    public void  yuyue(String orderId,String userId){
        Map<String,String>  map=new HashMap<>();
        map.put("id",""+orderId);
        map.put("userId",""+userId);
        Xutils.GET(HttpUrl.customizeorderUserMoneyPay, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject json=new JSONObject(result);

                    if(json.getBoolean("flag")){
                        Toast.makeText(getApplicationContext(),"购买成功",Toast.LENGTH_SHORT).show();
                        finish();
                    }else{
                        Toast.makeText(getApplicationContext(),"余额不足，购买失败",Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getApplicationContext(),"请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    //支付宝支付
    public void  zhifubao(String orderId,String userId){
        Map<String,String>  map=new HashMap<>();
        map.put("id",""+orderId);
        map.put("userId",""+userId);
        Xutils.GET(HttpUrl.customizeorderAliPay, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    final JSONObject json=new JSONObject(result);
                    if(json.getBoolean("flag")){
                        Toast.makeText(getApplicationContext(),"打开支付宝",Toast.LENGTH_SHORT).show();
                        Runnable payRunnable = new Runnable() {
                            @Override
                            public void run() {
                                PayTask alipay = new PayTask(PrivateGenicInfoActivity.this);
                                Map<String, String> result = null;
                                try {
                                    result = alipay.payV2(json.getString("data"), true);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                Message msg = new Message();
                                msg.what = HttpUrl.SDK_PAY_FLAG;
                                msg.obj = result;
                                mHandler.sendMessage(msg);
                            }
                        };
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();
                    }else{
                        Toast.makeText(getApplicationContext(),json.getString("msg"),Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getApplicationContext(),"请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
